package com.rainwen.consumer.hystrix;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.rainwen.api.dto.AccountDTO;
import com.rainwen.api.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 参考配置参数：https://github.com/Netflix/Hystrix/blob/master/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommandProperties.java
 * @author rain.wen
 * @date 2018/3/19.
 */
@Service
public class AccountServiceHystrix {

    private static final Logger logger = LoggerFactory.getLogger(AccountServiceHystrix.class);

    @Autowired
    private AccountService accountService;


    /**
     * 服务调用超时1秒，执行隔离，失败直接调用 reliable 方法
     * 服务恢复正常，取消隔离
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "reliable",
            groupKey = "accountCommandGroupKey",
            commandKey = "accountCommandKey",
            threadPoolKey = "accountThreadPoolKey",
            commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")})
    public AccountDTO getAccountById(Long id) {
        return accountService.getAccountById(id);
    }

    public AccountDTO reliable(Long id) {
        AccountDTO accountDTO = new AccountDTO();
        accountDTO.setId(0L);
        logger.info("hyxtrix call ");
        return accountDTO;
    }
}
